package com.huanghuang.shuadan.common.exception;

import com.huanghuang.shuadan.common.exception.base.BaseException;
import com.huanghuang.shuadan.common.exception.base.BaseExceptionEnum;
import com.huanghuang.shuadan.common.exception.business.BusinessException;
import com.huanghuang.shuadan.common.exception.user.UserException;
import com.huanghuang.shuadan.common.exception.vaild.Valid;
import com.huanghuang.shuadan.common.exception.vaild.ValidException;
import com.huanghuang.shuadan.service.entity.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author suxiaoxiao
 * @Date 2019/7/14 1:02
 * @Version 1.0
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class Handler {

    @ExceptionHandler(Exception.class)
    public Result exception(HttpServletRequest request, Exception e) {
        log.error("请求的url为{}出现系统异常,异常信息为:{}", request.getRequestURI(), e);
        return Result.error(BaseExceptionEnum.SYSTEM_BUSY);
    }

    @ExceptionHandler(BusinessException.class)
    public Result businessException(HttpServletRequest request, BusinessException e) {
        log.error("请求的url为{}出现业务异常,异常信息为:", request.getRequestURI(), e);
        return Result.error(e.getExceptionEnum());
    }

    @ExceptionHandler(UserException.class)
    public Result userException(HttpServletRequest request, UserException e) {
        log.error("请求的url为{}出现业务异常,异常信息为:", request.getRequestURI(), e);
        return Result.error(e.getExceptionEnum());
    }

    @ExceptionHandler(ValidException.class)
    public Result validException(HttpServletRequest request, ValidException e) {
        log.error("请求的url为{}出现业务异常,异常信息为:", request.getRequestURI(), e);
        Valid valid = e.getExceptionEnum();
        if (valid.getFieldName() == null) {
            return  Result.error(valid.getExceptionEnum());
        }
        return Result.error(valid.getExceptionEnum().getCode(),
                valid.getFieldName() + valid.getExceptionEnum().getMessage());
    }

}
